#include "mainwindow.h"
#include "liblive2d/Live2D.h"

#include <QMouseEvent>
#include <QVBoxLayout>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    live2d = new Live2D();
    live2d->showNormal();
    live2d->setFixedWidth(250);
    live2d->setFixedHeight(300);
    // live2d->setZoomFactor(qreal(1.3));

    QWidget *webWid = new QWidget();
    QVBoxLayout *webLayout = new QVBoxLayout(webWid);
    webLayout->addWidget(live2d);

    setCentralWidget(webWid);
    setWindowFlag(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    m_areaMovable = geometry();
    m_bPressed = false;



    QDesktopWidget *desktop = QApplication::desktop();
    move(desktop->width(), desktop->height());


}

MainWindow::~MainWindow()
{

}

void MainWindow::createRightClickMenu(const QPoint &pos)
{
    QMenu menu;
    QAction *act1 = menu.addAction("act1");
    connect(act1, &QAction::triggered, this, [=](){qDebug("clicked");});
    menu.exec(QCursor::pos());
}

void MainWindow::mousePressEvent(QMouseEvent *e)
{
    QWidget::mousePressEvent(e);
    if(e->button() == Qt::LeftButton) {
        m_ptPress = e->pos();
        m_bPressed = m_areaMovable.contains(m_ptPress);
    }
    if(e->button()==Qt::RightButton) {
        qDebug("rightClick");
        createRightClickMenu(e->pos());
    }
    e->ignore();
}

void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
    QWidget::mouseMoveEvent(e);
    if(m_bPressed) {
        move(pos() + e->pos() - m_ptPress);
    }
    e->ignore();
}

void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
    QWidget::mouseReleaseEvent(e);
    m_bPressed = false;
    e->ignore();
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(obj==live2d) {
        if(event->type()==QEvent::MouseButtonPress || QEvent::MouseMove || QEvent::MouseButtonRelease) {
            qDebug("mouse event on live2d");
        }
        qDebug("event on live2d");
    }
    if(obj==this) {
        qDebug("event on this");
    }
    return QMainWindow::eventFilter(obj, event);
}

void MainWindow::setAreaMovable(const QRect rt)
{
  if(m_areaMovable != rt) {
      m_areaMovable = rt;
  }
}

